local extension = Package:new("tea_ex_sp")
extension.extensionName = "wild_collection"
Fk:loadTranslationTable{
  ["tea_ex_sp"] = "茶水闲设·SP",
}
local U = require "packages/utility/utility"
local Est = require "packages/wild_collection/utility"

local zulang = General(extension, "tea__zulang", "wu", 4)
zulang.subkingdom = "qun"
local zhidai = fk.CreateViewAsSkill{
  name = "tea_zhidai",
  anim_type = "special",
  interaction = function()
    local all_names = {}
    if table.contains(Self:getTableMark("@tea_zhidai_mark-phase"), "zhidai_red_viewas") then
      table.insert(all_names, "slash")
    end
    if table.contains(Self:getTableMark("@tea_zhidai_mark-phase"), "zhidai_black_viewas") then
      table.insert(all_names, "analeptic")
    end
    local names = U.getViewAsCardNames(Self, "tea_zhidai", all_names)
    if #names > 0 then
      return UI.ComboBox { choices = names, all_choices = all_names }
    end
  end,
  card_filter = function(self, to_select, selected)
    if #selected == 0 then
      local colors = {}
      local mark = Self:getTableMark("@tea_zhidai_mark-phase")
      if self.interaction.data == "slash" and Fk:getCardById(to_select).color == Card.Red then
        return table.contains(mark, "zhidai_red_viewas")
      elseif self.interaction.data == "analeptic" and Fk:getCardById(to_select).color == Card.Black then
        return table.contains(mark, "zhidai_black_viewas")
      end
    end
  end,
  view_as = function(self, cards)
    if #cards ~= 1 or not self.interaction.data then return end
    local card = Fk:cloneCard(self.interaction.data)
    card:addSubcards(cards)
    card.skillName = self.name
    return card
  end,
  enabled_at_play = function(self, player)
    return player:getMark("@tea_zhidai_mark-phase") ~= 0
  end,
}
local zhidai_active = fk.CreateActiveSkill{
  name = "tea_zhidai_active",
  anim_type = "drawcard",
  card_filter = Util.FalseFunc,
  target_filter = Util.FalseFunc,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end, 
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    player:drawCards(1, zhidai.name)
    for i = 1, 100 do
      if not player:isKongcheng() then
        if table.find(player:getCardIds("h"), function(id)
          return Fk:getCardById(id).color ~= Fk:getCardById(player:getCardIds("h")[1]).color
        end) then break end
      end
      player:drawCards(1, zhidai.name)
    end
    player:showCards(player:getCardIds("h"))
    local redc = table.filter(player:getCardIds("h"), function(id)
      return Fk:getCardById(id).color == Card.Red
    end)
    local blackc = table.filter(player:getCardIds("h"), function(id)
      return Fk:getCardById(id).color == Card.Black
    end)
    local mark = {}
    if #redc <= #blackc then
      table.insert(mark, "zhidai_red_viewas")
    end
    if #redc >= #blackc then
      table.insert(mark, "zhidai_black_viewas")
    end
    room:setPlayerMark(player, "@tea_zhidai_mark-phase", mark)
  end,
}
local yintu = fk.CreateTriggerSkill{
  name = "tea_yintu",
  anim_type = "offensive",
  frequency = Skill.Compulsory,
  events = {fk.CardUseFinished},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) and target == player then
      local room = player.room
      local events = {}
      local turn_event = room.logic:getCurrentEvent():findParent(GameEvent.Turn, true)
      room.logic:getEventsByRule(GameEvent.UseCard, 999, function (e)
        local use = e.data[1]
        if use.from == player.id then
          table.insert(events, use)
        end
        return false
      end, turn_event.id)
      if #events == 1 then
        self.cost_data = events[1]
        return true
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local members = U.getActualUseTargets(room, self.cost_data, event)
    if #members > 0 then
      room:setPlayerMark(player, "tea_yintu_members-turn", members)
    end
  end,
}
local yintu_targetmod = fk.CreateTargetModSkill{
  name = "#tea_yintu_targetmod",
  bypass_times = function(self, player, skill, scope, card, to)
    if card and to and player:hasSkill(yintu, true) then
      local targetRecorded = player:getTableMark("tea_yintu_members-turn")
      return not table.contains(targetRecorded, to.id)
    end
  end,
  bypass_distances = function(self, player, skill, card, to)
    if card and to and player:hasSkill(yintu, true) then
      local targetRecorded = player:getTableMark("tea_yintu_members-turn")
      return not table.contains(targetRecorded, to.id)
    end
  end,
}
zhidai:addRelatedSkill(zhidai_active)
yintu:addRelatedSkill(yintu_targetmod)
zulang:addSkill(zhidai)
zulang:addSkill(yintu)
Fk:loadTranslationTable{
  ["tea__zulang"] = "祖郎",
  ["#tea__zulang"] = "至策危殆",
  ["designer:tea__zulang"] = "菖蒲",
  ["illustrator:tea__zulang"] = "XXX",
  ["cv:tea__zulang"] = "茶社",
  ["tea_zhidai"] = "至殆",
  [":tea_zhidai"] = "出牌阶段限一次，你可以摸一张牌并重复此流程直到手牌颜色不唯一，然后展示所有手牌，若红色牌数不大于/不小于黑色牌数，"..
  "此阶段你可以将红色/黑色牌当【杀】/【酒】使用。",
  ["tea_zhidai_active"] = "至殆",
  [":tea_zhidai_active"] = "",
  ["@tea_zhidai_mark-phase"] = "",
  ["zhidai_red_viewas"] = "<font color='red'>红</font>→杀",
  ["zhidai_black_viewas"] = "<font color='grey'>黑</font>→酒",
  ["tea_yintu"] = "阴图",
  [":tea_yintu"] = "锁定技，当你每回合首次使用牌结算结束后，你于本回合对非此牌目标的角色使用牌<a href='tea_yintu_extext'>无距离和次数限制</a>。",
  ["tea_yintu_extext"] = "这里谁充钱最多？......他妈的我顶死你！！！！！！！！！！！！！！",
}
local qiwannian = General(extension, "tea__qiwannian", "jin", 4)
qiwannian.subkingdom = "qun"
local kouhuo = fk.CreateTriggerSkill{
  name = "tea_kouhuo",
  mute = true,
  events = {fk.CardUseFinished},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self.name) and data.extra_data then
      return data.extra_data.tea_kouhuo_slash
    end
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    if data.extra_data.tea_kouhuo_damage ~= player.id then
      player:drawCards(1, self.name)
    end
    if data.damageDealt then
      target:drawCards(1, self.name)
    end
  end,
  refresh_events = {fk.EventAcquireSkill, fk.EventLoseSkill, fk.BuryVictim, fk.AfterPropertyChange, fk.Damaged},
  can_refresh = function(self, event, target, player, data)
    if event == fk.EventAcquireSkill or event == fk.EventLoseSkill then
      return data == self
    elseif event == fk.BuryVictim then
      return target:hasSkill(self, true, true)
    elseif event == fk.AfterPropertyChange then
      return target == player
    elseif event == fk.Damaged then
      if target == player and player:hasSkill(self, true) then
        local room = player.room
        local turn_event = room.logic:getCurrentEvent():findParent(GameEvent.Turn)
        local events = {}
        if turn_event then
          room.logic:getEventsByRule(GameEvent.UseCard, 999, function (e)
            local use = e.data[1]
            if use.card == data.card and (use.extra_data or {}).tea_kouhuo_slash then
              table.insert(events, use)
            end
          end, turn_event.id)
        end
        if #events > 0 then
          local use = events[1]
          self.cost_data = use
          return (use.extra_data or {}).tea_kouhuo_slash
        end
      end
    end
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    if event == fk.Damaged then
      self.cost_data.extra_data.tea_kouhuo_damage = player.id
    else
      local attached = table.find(room.alive_players, function (p)
        return p:hasSkill(self)
      end)
      if attached and not player:hasSkill("tea_kouhuo&", true, true) then
        room:handleAddLoseSkills(player, "tea_kouhuo&", nil, false, true)
      elseif not attached and player:hasSkill("tea_kouhuo&", true, true) then
        room:handleAddLoseSkills(player, "-tea_kouhuo&", nil, false, true)
      end
    end
  end,
}
local kouhuo_viewas = fk.CreateViewAsSkill{
  name = "tea_kouhuo&",
  mute = true,
  pattern = "slash",
  prompt = "#tea_kouhuo_viewas-invoke",
  interaction = function()
    local all_names = {"slash"}
    local names = U.getViewAsCardNames(Self, "tea_kouhuo&", all_names, Self:getCardIds("he"))
    if #names > 0 then
      return U.CardNameBox { choices = names, all_choices = all_names }
    end
  end,
  card_filter = function(self, to_select, selected)
    return #selected == 0 and self.interaction.data
  end,
  view_as = function(self, cards)
    if #cards ~= 1 or not self.interaction.data then return end
    local card = Fk:cloneCard(self.interaction.data)
    card:addSubcards(cards)
    card.skillName = self.name
    return card
  end,
  before_use = function(self, player, use)
    if not use.extra_data then
      use.extra_data = {}
    end
    use.extra_data.tea_kouhuo_slash = true
    Fk:currentRoom():notifySkillInvoked(player, self.name, "special")
  end,
  enabled_at_play = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryTurn) == 0
  end,
  enabled_at_response = function(self, player, response)
    return not response and player:usedSkillTimes(self.name, Player.HistoryTurn) == 0
  end,
}
local zhaoluan = fk.CreateTriggerSkill{
  name = "tea_zhaoluan",
  anim_type = "big",
  frequency = Skill.Compulsory,
  events = {fk.GameStart, fk.Deathed},
  can_trigger = function(self, event, target, player, data)
    return (event == fk.GameStart and player:hasSkill(self)) or (event == fk.Deathed and target == player and player:hasSkill(self, false, true))
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local targets = table.map(room.alive_players, Util.IdMapper)
    room:sortPlayersByAction(targets)
    local card = Fk:cloneCard("slash")
    for _, id in ipairs(targets) do
      local p = room:getPlayerById(id)
      local can_cancel = table.find(p:getCardIds("he"), function(cid)
        return not p:prohibitDiscard(cid)
      end) and not p:isNude()
      local can_choose = can_cancel or (p:canUse(card, {bypass_distances = true}) and table.find(room:getOtherPlayers(p), function(p2)
        return p:canUseCardTo(card, p2, {bypass_distances = true})
      end))
      if not p.dead and can_choose  then
        local use = room:askForUseCard(p, nil, "slash", "#tea_zhaoluan-use", can_cancel, {
          extraUse = true,
          bypass_distances = true,
        })
        if use then
          room:useCard(use)
        else
          local cid = room:askForDiscard(p, 1, 1, true, self.name, false, ".", "#tea_zhaoluan-discard")
        end
      end
    end
  end,
}
Fk:addSkill(kouhuo_viewas)
qiwannian:addSkill(kouhuo)
qiwannian:addSkill(zhaoluan)
Fk:loadTranslationTable{
  ["tea__qiwannian"] = "齐万年",
  ["#tea__qiwannian"] = "寇乱之始",
  ["designer:tea__qiwannian"] = "布林",
  ["illustrator:tea__qiwannian"] = "率土之滨",
  ["cv:tea__qiwannian"] = "茶社",
  ["tea_kouhuo"] = "寇祸",
  [":tea_kouhuo"] = "每名角色的回合限一次，当其需要使用【杀】时，其可以将一张牌当【杀】使用，若你未因此受到伤害，你摸一张牌；若其因此造成伤害，其摸一张牌。",
  ["tea_kouhuo&"] = "寇祸",
  [":tea_kouhuo&"] = "每回合限一次，你可以将一张牌当【杀】使用。",
  ["#tea_kouhuo_viewas-invoke"] = "你可以将一张牌当【杀】使用",
  ["tea_zhaoluan"] = "肇乱",
  [":tea_zhaoluan"] = "锁定技，<a href='tea_piaobo_zhaoluan'>游戏开始时和你死亡后</a>，每名角色依次选择一项：1.弃一张牌；2.使用一张无距离限制的【杀】。",
  ["tea_piaobo_zhaoluan"] = "哈里路大旋风！！！！",
  ["#tea_zhaoluan-use"] = "肇乱：你须使用一张【杀】，或点击取消并弃置一张牌。",
  ["#tea_zhaoluan-discard"] = "肇乱：你须弃置一张牌",
}
local liuezhi = General(extension, "tea__liuezhi", "jin", 3)
liuezhi.subkingdom = "qun"
local getCountry = function(player)
  if player:getMark("@tea_piaobo_mark") ~= 0 then
    return player:getMark("@tea_piaobo_mark")
  else
    return "china"
  end
end
local changeCountry = function(room, player)
  local mark = getCountry(player)
  local from, to
  if mark == "china" then
    mark = "japan"
    from = "china"
    to = "japan"
  elseif mark == "japan" then
    mark = "china"
    from = "japan"
    to = "china"
  end
  local event_data = {
    from = from,
    to = to,
  }
  room:setPlayerMark(player, "@tea_piaobo_mark", mark)
  room:sendLog{
    type = "#EnterOneCountry",
    from = player.id,
    arg = from,
    arg2 = to,
  }
  room.logic:trigger("fk.AfterCountryChanged", player, event_data)
  return {from, to}
end
local piaobo = fk.CreateTriggerSkill{
  name = "tea_piaobo",
  anim_type = "special",
  frequency = Skill.Compulsory,
  events = {fk.GameStart},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self, true)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    for _, p in ipairs(room.alive_players) do
      room:setPlayerMark(p, "@tea_piaobo_mark", "china")
    end
    changeCountry(room, player)
  end,
}
local piaobo_trigger = fk.CreateTriggerSkill{
  name = "#tea_piaobo_trigger",
  anim_type = "special",
  mute = true,
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self, true, true) and target.phase == Player.Start and not target:isNude()
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local cid = room:askForDiscard(target, 1, 1, true, piaobo.name, true, ".", "#tea_piaobo-invoke", true)
    if #cid > 0 then
      self.cost_data = cid
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:throwCard(self.cost_data, piaobo.name, target, target)
    if not target.dead then
      changeCountry(room, target)
    end
  end,
}
local piaobo_prohibit = fk.CreateProhibitSkill{
  name = "#tea_piaobo_prohibit",
  frequency = Skill.Compulsory,
  is_prohibited = function(self, from, to)
    return getCountry(from) ~= getCountry(to)
  end,
}
local piaobo_distance = fk.CreateDistanceSkill{
  name = "#tea_piaobo_distance",
  frequency = Skill.Compulsory,
  correct_func = function(self, from, to)
    local arr1 = {}
    local arr2 = {}
    local p = from:getNextAlive()
    for i = 1, 15 do
      if p == to or p == from then break end
      table.insert(arr1, p)
      p = p:getNextAlive()
    end
    p = from:getLastAlive()
    for i = 1, 15 do
      if p == to or p == from then break end
      table.insert(arr2, p)
      p = p:getLastAlive()
    end
    local find1 = table.filter(arr1, function(p1)
      return getCountry(p1) ~= getCountry(from)
    end)
    local find2 = table.filter(arr2, function(p2)
      return getCountry(p2) ~= getCountry(from)
    end)
    if #arr1 < #arr2 then
      return - #find1
    elseif #arr1 > #arr2 then
      return  - #find2
    else
      return -(math.max(#find1, #find2))
    end
  end,
}
local yifeng = fk.CreateTriggerSkill{
  name = "tea_yifeng",
  anim_type = "special",
  frequency = Skill.Compulsory,
  events = {"fk.AfterCountryChanged"},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) then
      return (player == target and getCountry(player) == "japan") or (player ~= target and getCountry(target) == getCountry(player))
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if player == target then
      room:changeMaxHp(player, 1)
    else
      player:drawCards(1, self.name)
      target:drawCards(1, self.name)
    end
  end,
}
local yanzhong = fk.CreateTriggerSkill{
  name = "tea_yanzhong",
  anim_type = "drawcard",
  events = {fk.Damage, fk.Damaged, fk.EventAcquireSkill},
  can_trigger = function(self, event, target, player, data)
    if event == fk.EventAcquireSkill then
      return false
    else
      return player:hasSkill(self) and target == player and table.find(player.room:getOtherPlayers(player), function(p)
        return not p:hasSkill(self, true)
      end)
    end
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    if event == fk.EventAcquireSkill then
      return true
    else
      local targets = table.map(table.filter(room:getOtherPlayers(player), function(p)
        return not p:hasSkill(self, true)
      end), Util.IdMapper)
      if #targets > 0 then
        local to, cid = room:askForChooseCardAndPlayers(player, targets, 1, 1, ".", "#tea_yanzhong-invoke", self.name, true)
        if #to == 1 and cid then
          self.cost_data = {to[1], cid}
          return true
        end
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.EventAcquireSkill then
      player:drawCards(1, self.name)
    else
      local to = room:getPlayerById(self.cost_data[1])
      local cid = self.cost_data[2]
      room:obtainCard(to, cid, false, fk.ReasonGive, player.id)
      room:handleAddLoseSkills(to, self.name, nil, false)
      for _, p in ipairs(room:getOtherPlayers(to)) do
        if p:hasSkill(self) then
          p:drawCards(1, self.name)
        end
      end
    end
  end,
}
piaobo:addRelatedSkill(piaobo_trigger)
piaobo:addRelatedSkill(piaobo_prohibit)
piaobo:addRelatedSkill(piaobo_distance)
liuezhi:addSkill(piaobo)
liuezhi:addSkill(yifeng)
liuezhi:addSkill(yanzhong)
Fk:loadTranslationTable{
  ["tea__liuezhi"] = "刘阿知",
  ["#tea__liuezhi"] = "携族避乱",
  ["designer:tea__liuezhi"] = "布林",
  ["illustrator:tea__liuezhi"] = "啪啪三国",
  ["cv:tea__liuezhi"] = "茶社",
  ["tea_piaobo"] = "漂泊",
  [":tea_piaobo"] = "锁定技，<a href='tea_piaobo_extext'>游戏开始时</a>，你将场上分为“<font color='red'>华夏</font>”与“<font color='green'>倭国</font>”两个区划，其他角色默认位于“<font color='red'>"..
  "华夏</font>”，你进入“<font color='green'>倭国</font>”。每名角色使用牌仅可指定同区划内的角色，且计算距离时仅计算同区划内的角色。每名角色的准备阶段，其可以弃一张牌并进"..
  "入另一个区划。",
  ["tea_piaobo_extext"] = "ははは、実は私はとっくに日本人ですね！～",
  ["#tea_piaobo_trigger"] = "漂泊",
  ["@tea_piaobo_mark"] = "区划",
  ["china"] = "<font color='red'>华夏</font>",
  ["japan"] = "<font color='green'>倭国</font>",
  ["#tea_piaobo-invoke"] = "漂泊：你可以弃置一张牌迁移至另一地区",
  ["#tea_piaobo_prohibit"] = "漂泊",
  ["#EnterOneCountry"] = "%from 从 %arg 进入了 %arg2",
  ["tea_yifeng"] = "夷封",
  [":tea_yifeng"] = "锁定技，你进入“<font color='green'>倭国</font>”后加1点体力上限；其他角色进入你所在区划后，你与其各摸一张牌。",
  ["tea_yanzhong"] = "衍众",
  [":tea_yanzhong"] = "当你造成或受到伤害后，你可以交给一名其他角色一张牌并令其获得“衍众”。当有角色获得“衍众”后，你摸一张牌。",
  ["#tea_yanzhong-invoke"] = "衍众：你可以将一张牌交给一名其他角色并令其获得“衍众”",
}

return extension